package com.fancy.social.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fancy.social.dto.LikeDTO;
import com.fancy.social.entity.LikeRecord;
import com.fancy.social.mapper.LikeRecordMapper;
import com.fancy.social.service.LikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class LikeServiceImpl implements LikeService {

    @Autowired
    private LikeRecordMapper likeRecordMapper;

    @Override
    public void toggleLike(Long userId, LikeDTO likeDTO) {
        QueryWrapper<LikeRecord> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                .eq("target_id", likeDTO.getTargetId())
                .eq("target_type", likeDTO.getTargetType());
        LikeRecord existingLike = likeRecordMapper.selectOne(queryWrapper);

        if ("like".equalsIgnoreCase(likeDTO.getAction())) {
            if (existingLike == null) {
                LikeRecord newLike = new LikeRecord();
                newLike.setUserId(userId);
                newLike.setTargetId(likeDTO.getTargetId());
                newLike.setTargetType(likeDTO.getTargetType());
                newLike.setCreateTime(LocalDateTime.now());
                likeRecordMapper.insert(newLike);
                // Note: Incrementing the like_count on the target entity should be handled here
                // This might involve another service call or a direct update if the table is in the same database.
            }
        } else if ("unlike".equalsIgnoreCase(likeDTO.getAction())) {
            if (existingLike != null) {
                likeRecordMapper.deleteById(existingLike.getId());
                // Note: Decrementing the like_count should be handled here.
            }
        }
    }
}

